package com.wom.gui;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;

import com.wom.worldmaker.GameProperties;
import com.wom.worldmaker.GameWorld;



public class GameApplet extends Applet implements Runnable{




	private static final long serialVersionUID = 1L;
	private boolean running;
	public BlockTypes addBlockType;
	private FPSCounter fpsCounter=new FPSCounter();
	public GameWorld gameWorld=new GameWorld(this);;
	public String mouseOnBlock="None";
	
	
	public static int fps=0;
	
	
	private Image img;
	




	public GameApplet(Dimension size) {
		setSize(size);
		
		addBlockType=BlockTypes.Dirt;
		addKeyListener(new KeyHandler(this));
		addMouseMotionListener(new MouseHandler());
		addMouseListener(new MouseHandler());
				
		
		
		
		

	}

	public void init(){

		
		Thread thread=new Thread(this);
		thread.start();
	}


	@Override
	public void run() {
		running=true;
		//img=createVolatileImage(800, 600);
		
		System.out.println("Running...");
		img=new BufferedImage(GameProperties.windowSize.width, GameProperties.windowSize.height,BufferedImage.TYPE_INT_RGB);
		
		Graphics g=img.getGraphics();
		
		fpsCounter.startCounter();

		while(running){
			
			
			//fpsCounter.startCounter();
			updateStuff();
			renderStuff(g);
			
				
			try {
				Thread.sleep(6);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			fpsCounter.calculateFPS();
			
			
			
		}
		System.out.println("ending");



	}

	private void updateStuff() {
		
		gameWorld.updatePlayer();
		gameWorld.updateWorld();
		
	}

	

	private void renderStuff(Graphics g) {
		g.setColor(Color.BLACK);
		g.fillRect(0, 0,GameProperties.windowSize.width,GameProperties.windowSize.height);
		g.setColor(Color.WHITE);

		
		gameWorld.renderWorld(g);
		
		g=getGraphics();
		g.drawImage(img, 0,
				0,
				GameProperties.windowSize.width,
				GameProperties.windowSize.height,
				0,
				0,
				GameProperties.pixelSize.width,
				GameProperties.pixelSize.height,
				null);
		
		
		
		g.setColor(Color.WHITE);
		g.drawString(mouseOnBlock,0 ,20);
		g.drawString((int)GameWorld.player.x+ ":"+ (int)GameWorld.player.y,0 ,40);
		g.drawString("FPS:"+fps,0 ,60);
		g.drawString("Camera coord:"+(int)GameWorld.player.cam.x+","+(int)GameWorld.player.cam.y,0 ,80);
		g.drawString("Walking dir:"+GameWorld.player.xDirection,0 ,100);
		g.drawString("walking:"+GameWorld.player.walking,0 ,120);
		g.drawString("mouse 1"+GameWorld.player.mousePressedLeft+", 2:"+GameWorld.player.mousePressedRight,0 ,140);
		g=getGraphics();
		g.dispose();

	}

	
	

	
	
	
	
}

